package com.cy.controller;

import com.cy.entity.Director;
import com.cy.entity.Movie;
import com.cy.entity.Tj;
import com.cy.service.MService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class MController {
    @Autowired
    MService service;
    @RequestMapping("list")
    public String list(Tj tj, @RequestParam(defaultValue = "1") Integer pageNum, Model model){
        PageInfo<Movie> pg = service.list(tj,pageNum);
        model.addAttribute("pg",pg);
        model.addAttribute("tj",tj);
        return "list";
    }

    @RequestMapping("del")
    public String del(Integer id){
        service.del(id);
        return "redirect:list";
    }

    @RequestMapping("add")
    public String add(Model model){
        List<Director> list = service.dir();
        model.addAttribute("movie",new Movie());
        model.addAttribute("dir",list);
        return "insert";
    }

    @RequestMapping("file")
    @ResponseBody
    public String file(MultipartFile file,Model model) throws IOException {
        String path = "c://img";
        String filename= UUID.randomUUID().toString()+file.getOriginalFilename();
        File file1 = new File(path, filename);
        if(!file1.exists()){
            file1.mkdirs();
        }
        file.transferTo(file1);
        return "/img/"+filename;
    }

    @RequestMapping("insert")
    public String insert(Movie movie,Model model){
        service.insert(movie);
        return "redirect:list";
    }

    @RequestMapping("sel")
    public String sel(Integer id,Model model){
        Movie movie = service.sel(id);
        model.addAttribute("movie",movie);
        model.addAttribute("dir",service.dir());
        return "update";
    }

    @RequestMapping("update")
    public String update(Movie movie,Model model){
        service.update(movie);
        return "redirect:list";
    }
}
